package com.example.minato.minastore.log;


import com.orhanobut.logger.Logger;

import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Creater: Created by wangyz on 2017/2/21.
 * Email: 936804097@qq.com
 */

public class LoggingInterceptor implements Interceptor {

//    private String token;

    public LoggingInterceptor() {
    }

//    public LoggingInterceptor(String token) {
//        this.token = token;
//    }


    boolean isPlaintext(Buffer buffer) throws EOFException {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (EOFException e) {
            return false; // Truncated UTF-8 sequence.
        }
    }

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();

        long t1 = System.nanoTime();




        String method = request.method();
        if ("POST".equals(method)) {
            StringBuilder sb = new StringBuilder();
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                for (int i = 0; i < body.size(); i++) {
                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
                }
                sb.delete(sb.length() - 1, sb.length());
                Logger.i("---------------------------------{" + sb.toString() + "}");
            } else {
                RequestBody requestBody = request.body();
                if (requestBody != null) {
                    Buffer buffer = new Buffer();
                    requestBody.writeTo(buffer);
                    Charset UTF8 = Charset.forName("UTF-8");
                    Charset charset = UTF8;
                    MediaType contentType = requestBody.contentType();
                    if (contentType != null) {
                        charset = contentType.charset(UTF8);
                    }
                    if (isPlaintext(buffer)) {
//                        Logger.i("-------------------------s--------" + buffer.readString(charset));
                    } else {
                        Logger.i("--------------------------------- " + request.method() + " (binary "
                                + requestBody.contentLength() + "-byte body omitted)");
                    }
                }
            }
        }

//           Request compressedRequest = request.newBuilder()
//                   .header("token", this.token).build();
        Request compressedRequest = request.newBuilder().build();
        if (request.url().toString().contains("befSave")){
            compressedRequest = request;
        }

//        Logger.i(String.format("request--------------------------token:  %s",this.token));
        Logger.i(String.format("request---------------------------  %s on %s%n%s--%s",
                compressedRequest.url(), chain.connection(), compressedRequest.headers(), compressedRequest.method()));


        Response response = chain.proceed(compressedRequest);

        long t2 = System.nanoTime();
        Logger.i(String.format("response----------------- for %s in %.1fms%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers()));
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        int i;
//        while ((i = response.body().byteStream().read()) != -1) {
//            baos.write(i);
//        }
//        Logger.i("-----data-----%s", baos.toString());

        return response;
//        return chain.proceed(compressedRequest);
    }


}